<?php
declare (strict_types = 1);

namespace app\controller\adminapi\v1\setting;



use app\services\admin\setting\PermissionServices;
//use app\dao\admin\PermissionDao;

use app\BaseController;

use app\Request;


//use think\App;
//use think\facade\Config;
use think\facade\Db;
use think\facade\Cache;


use support\Container;


use Exception;



class PermissionController extends BaseController
{

    /**
     * 构造方法
     * PermissionServices constructor.
     */
	public function __construct()
	{
        //$this->services = new PermissionServices;
        $this->services = Container::get(PermissionServices::class);
	}
    


	/**
		* 显示资源列表
		*
		* @return \support\Response
	*/
	public function index(Request $request)
	{
		/** @var RoleServices $services */
		//$services = app()->make(RoleServices::class);

		
        $where = $request->getParams([
            ['name'],
            //['delete_time', null],
            ['status', null],	//null表示使用 search搜索器的 软删除（>=-1）
        ]);


		static::validate($where, [
			'name' => 'max:32',
			'status' => 'in:0,1',
		], [], true, true);

		
		$ret = $this->services->getList($where, null, null,
			"id, pid, name, icon, type, status, show, api_path, methods, menu_path, sort, unique_auth", 
			['sort', 'ASC']
		)->toArray();
			
        return ret_value(0, "", $ret);
	}

    /**
	* 新建
	*
	* @param  \app\Request  $request
	* @return \support\Response
	*/
	public function store(Request $request)
	{
        $data = $request->getParams([
            ['pid', 0],
            ['name'],
            ['type', 0],
            ['status', 0],
            ['sort', 0],
            ['api_path'],
            ['methods', ''],
            ['show', 0],
            ['icon', ''],
            ['menu_path', ''],
        ]);

        
		static::validate($data, [
            'pid' => 'require|integer',
			'name' => 'require|max:32',
			'type' => 'require|integer',
			'status' => 'in:0,1',
			'sort' => 'require|integer',
			'api_path' => 'max:255',
			'methods' => 'in:POST,GET,PUT,DELETE',
			'show' => 'require|integer',
			'icon' => 'max:32',
			'menu_path' => 'max:255',
		], [], true, true);


        // $data['level'] = $this->adminInfo['level'] + 1;
        /*
        try {
			$this->services->save($data);
        }
		catch (\RuntimeException $e) {
			return ret_value(-1, $e->getMessage());
		}
		catch (\Exception $e) {
			return ret_value(-1, $e->getMessage());
		}
        */
        
		$this->services->save($data);
        return ret_value(0, "Success");
	}
	
	/**
	 * 显示指定的资源
	 *
	 * @param  string  $id
	 * @return \support\Response
	*/
	public function show(Request $request, $id)
	{
		/*$t1 = \think\facade\Db::connect('local')
		->table('lms_user_info')
		->where('id', $id)
		->find();

		return json($t1);
		*/


		if(strpos($id, '_') !== false)
		{
			$ids = explode('_', $id);
			$where = [['id', 'in', $ids]];
		}
		else {
			$where = ['id' => $id];
		}
        //$where['level'] = $this->adminInfo['level'] + 1;
        //return app('json')->success($this->services->getList($where));

		/** @var PermissionServices $services */
		//$services = app()->make(UserServices::class);

		$ret = $this->services->selectList($where, null, null,
			'*', ['sort', 'ASC']
		)->toArray();

        return ret_value(0, "", $ret);
	}
	
    /**
     * 修改
     * @param $id
     * @return mixed
     */
    public function update(Request $request, $id)
    {
        $data = $request->getParams([
            ['id', $id],
            ['pid'],
            ['name'],
            ['icon'],
            ['type'],
            ['status'],
            ['show'],
            ['api_path'],
            ['methods'],
            ['menu_path'],
            ['sort'],
            ['unique_auth'],
            ['delete_time'],
        ]);

        
		static::validate($data, [
            'id' => 'require|integer',
            'pid' => 'integer',
			'name' => 'max:32',
			'type' => 'integer',
			'status' => 'in:0,1',
			'sort' => 'integer',
			'api_path' => 'max:255',
			'methods' => 'in:POST,GET,PUT,DELETE',
			'show' => 'integer',
			'icon' => 'max:32',
			'menu_path' => 'max:255',
		], [], true, true);
        

		$ret = $this->services->update((int)$id, $data);
        if ($ret)
		{
			return ret_value(0, "Success");
        }
		else
		{
			return ret_value(-1, "Fail");
        }
    }

    /**
	 * 删除指定资源（$id为单个数字 或 多个用_分隔的数字）
	 * @param int|string $id
	 * @return \support\Response
    */
    public function destroy(Request $request, $id)
    {
        $data = $request->getParams([
            ['data', $id],
		]);
		static::validate($data, [
			'data' => 'require',
		]);


		//var_dump($id);
        //$ids = is_array($id) ? $id : (is_string($id) ? explode(',', $id) : func_get_args());
		$ids = explode('_', $data["data"]);
		//var_dump($request->param());
		//var_dump($ids);
        //if (!$id) return app('json')->fail('删除失败，缺少参数');
		$ret = $this->services->batchUpdate($ids, ['status' => -1, 'delete_time' => date("Y-m-d H:i:s")]);
		//var_dump($ret);
        if ($ret)
            return ret_value(0, "Success");
        else
            return ret_value(-1, "Fail");
    }
}
